package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.domain.pojo.User;
import com.tanhua.sso.mapper.UserMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${jwt.secret}")
    private String secret;//注入存在yml里的盐("${}")

    /**
     * 登录逻辑
     * @param mobile
     * @param code
     * @return 如果校验成功, 返回token, 如果失败返回mull
     */
    public String login(String mobile, String code) {
        //校验验证码是否正确--连接redis注入RedisTemplate<String, String>
        String redisKey = "CHECK_CODE_" + mobile;
        String value = this.redisTemplate.opsForValue().get(redisKey);
        //判断是否为空
        if (StringUtils.isEmpty(value)) {
            //验证码失效
            return null;
        }
        //判断是否相等
        if (!StringUtils.equals(value, code)) {
            //验证码输入错误
            return null;
        }

        //校验该手机号是否已经注册,如果没有注册,需要注册一个账号,如果已经注册,则直接登录
        Boolean isNew = false;//默认已注册

        User selectUser = userMapper.selectByMobile(mobile);
        if (selectUser == null) {
            // 该手机号未注册，进行注册操作
            selectUser = new User();
            selectUser.setMobile(mobile);
            // 默认密码
            selectUser.setPassword(DigestUtils.md5Hex(secret + "_123456"));
            this.userMapper.insert(selectUser);
            isNew = true;//未注册的用户
        }

        //生成token的逻辑
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("mobile", mobile);
        claims.put("id", selectUser.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //设置响应数据体
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .compact();

        //将用户数据写入到redis中
        String redisTokenKey = "TOKEN_" + token;
        try {
            this.redisTemplate.opsForValue().set(redisTokenKey, MAPPER.writeValueAsString(selectUser), Duration.ofHours(1));
        } catch (Exception e) {
            e.printStackTrace();//出异常要记录
        }

        try {
            // 发送登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("userId", selectUser.getId());
            msg.put("date", new Date());
            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);//发送消息
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isNew + "|" + token;
    }

    /**
     * 按token查询用户
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        try {
            String redisTokenKey = "TOKEN_" + token;
            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isEmpty(cacheData)) {
                return null;
            }
            // 刷新时间
            this.redisTemplate.expire(redisTokenKey, 1, TimeUnit.HOURS);
            return MAPPER.readValue(cacheData, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
